import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class TransactionExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://lacalhost:3360/your_database";
        String username = "your_username";
        String password = "your_password";

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(jdbcUrl,username,password);

            connection.setAutoCommit(false);

            Statement statement = connection.createStatement();
            statement.executeUpdate("INSERT INTO your_table(column1, column2) VALUES (value1, value2)");
            statement.executeUpdate("UPDATE your_table SET column1 = new_value WHERE condition");

            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                // 如果发生异常，回滚事务
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException rollbackException) {
                rollbackException.printStackTrace();
            }
        } finally {
            try {
                // 恢复默认的自动提交模式
                if (connection != null) {
                    connection.setAutoCommit(true);
                    connection.close();
                }
            } catch (SQLException closeException) {
                closeException.printStackTrace();
            }
        }
    }
}
